// src/components/sponsorDashboard/mainContent/ColumnSelector.tsx

import type { FC } from 'react';
import { useCallback, useMemo } from 'react';
import { FiLock, FiCheckSquare, FiXSquare, FiX } from 'react-icons/fi';
import { useState } from 'react';

interface HeaderOption {
  key: string;
  label: string;
}

interface ColumnSelectorProps {
  allHeaders: HeaderOption[];
  selectedHeaders: string[];
  updateSelectedHeaders: (keys: string[]) => void;
}

const ColumnSelector: FC<ColumnSelectorProps> = ({
  allHeaders,
  selectedHeaders,
  updateSelectedHeaders,
}) => {
  const [showOptions, setShowOptions] = useState(false);

  const dependencyMap = useMemo((): Record<string, string[]> => ({
    company_name: ['sponsor_id'],
    program_code: ['program_id', 'program_length'],
  }), []);

  const parentMap = useMemo(() => {
    const map: Record<string, string> = {};
    Object.entries(dependencyMap).forEach(([parent, children]) => {
      children.forEach((child) => {
        map[child] = parent;
      });
    });
    return map;
  }, [dependencyMap]);

  const toggleHeader = useCallback(
    (key: string) => {
      const isSelected = selectedHeaders.includes(key);
      let updated = [...selectedHeaders];

      const children = dependencyMap[key] || [];

      if (isSelected) {
        updated = updated.filter((h) => h !== key && !children.includes(h));
      } else {
        updated.push(key);
        children.forEach((child: string) => {
          if (!updated.includes(child)) updated.push(child);
        });
      }

      updateSelectedHeaders(updated);
    },
    [selectedHeaders, updateSelectedHeaders, dependencyMap]
  );

  return (
    <div className="w-full px-4 sm:px-6 py-3 mb-2 font-poppins">
      {/* Always show a single button per row to open column selector */}
      <div className="flex justify-center items-center">
        <button
          onClick={() => setShowOptions((v) => !v)}
          className="w-full max-w-lg flex items-center justify-center gap-3 px-4 py-3 text-base rounded-xl border border-blue-400 text-blue-700 dark:text-cyan-300 bg-white dark:bg-slate-800 shadow-md hover:bg-blue-50 dark:hover:bg-slate-700 hover:shadow-lg transition-all duration-200 font-medium focus:outline-none focus:ring-2 focus:ring-blue-400 dark:focus:ring-cyan-700 focus:ring-offset-2"
          style={{ letterSpacing: '0.01em' }}
        >
          {showOptions ? <FiX className="text-blue-500 dark:text-cyan-300 text-lg" /> : <FiCheckSquare className="text-blue-500 dark:text-cyan-300 text-lg" />}
          {showOptions ? 'Close Column Selector' : 'Choose Columns'}
        </button>
      </div>
      {/* Popup selection for all screens */}
      <div className="flex flex-col items-center">
        {showOptions && (
          <div className="relative animate-fade-in-up mt-3 p-4 rounded-2xl border border-gray-200 dark:border-slate-700 shadow-xl bg-white dark:bg-slate-800 z-30 flex flex-col gap-4 w-full max-w-4xl transition-all duration-300">
            {/* Close button */}
            <button
              onClick={() => setShowOptions(false)}
              className="absolute top-3 right-3 text-gray-400 dark:text-gray-500 hover:text-blue-500 dark:hover:text-cyan-300 text-lg focus:outline-none focus:ring-2 focus:ring-blue-400 dark:focus:ring-cyan-700 rounded-full p-1 transition-all duration-200"
              aria-label="Close column selector"
            >
              <FiX />
            </button>
            {/* Select/Clear all row */}
            <div className="flex gap-3 mb-2 justify-center">
              <button
                onClick={() => updateSelectedHeaders(allHeaders.map((h) => h.key))}
                className="flex items-center gap-2 px-4 py-2 text-sm rounded-xl border border-blue-400 dark:border-cyan-700 text-blue-700 dark:text-cyan-300 bg-blue-50 dark:bg-slate-700 hover:bg-blue-100 dark:hover:bg-cyan-800 active:bg-blue-200 dark:active:bg-cyan-900 shadow-sm font-medium focus:outline-none focus:ring-2 focus:ring-blue-300 dark:focus:ring-cyan-700 transition-all duration-200"
              >
                <FiCheckSquare className="text-blue-500 dark:text-cyan-300" />
                Select All
              </button>
              <button
                onClick={() => updateSelectedHeaders([])}
                className="flex items-center gap-2 px-4 py-2 text-sm rounded-xl border border-red-300 text-red-600 dark:text-red-300 bg-red-50 dark:bg-slate-700 hover:bg-red-100 dark:hover:bg-red-800 active:bg-red-200 dark:active:bg-red-900 shadow-sm font-medium focus:outline-none focus:ring-2 focus:ring-red-200 dark:focus:ring-red-700 transition-all duration-200"
              >
                <FiXSquare className="text-red-400 dark:text-red-300" />
                Clear All
              </button>
            </div>
            <div className="border-t border-gray-100 dark:border-slate-700 my-2" />
            {/* Column options */}
            <div className="flex flex-wrap gap-3 justify-center">
              {allHeaders.map(({ key, label }) => {
                const parent = parentMap[key];
                // Child is only highlighted if its key is in selectedHeaders
                const isSelected = selectedHeaders.includes(key);
                const isDisabled = parent ? !selectedHeaders.includes(parent) : false;
                return (
                  <button
                    key={key}
                    onClick={() => !isDisabled && toggleHeader(key)}
                    disabled={isDisabled}
                    className={`flex items-center gap-2 px-3 py-2 text-sm rounded-xl font-medium whitespace-nowrap shadow-sm focus:outline-none focus:ring-2 transition-all duration-200
                      ${isDisabled
                        ? 'bg-gray-100 dark:bg-slate-700 text-gray-400 border border-gray-200 dark:border-slate-700 cursor-not-allowed'
                        : isSelected
                          ? 'bg-blue-600 dark:bg-cyan-700 text-white border border-blue-600 dark:border-cyan-700 hover:bg-blue-700 dark:hover:bg-cyan-800 focus:ring-blue-300 dark:focus:ring-cyan-700 shadow-md'
                          : 'bg-white dark:bg-slate-800 text-gray-700 dark:text-gray-100 border border-gray-300 dark:border-slate-700 hover:bg-blue-50 dark:hover:bg-slate-700 hover:border-blue-300 dark:hover:border-cyan-700 focus:ring-blue-200 dark:focus:ring-cyan-700'}
                    `}
                    tabIndex={isDisabled ? -1 : 0}
                    aria-disabled={isDisabled}
                    aria-pressed={isSelected}
                    style={{ letterSpacing: '0.01em' }}
                  >
                    {isDisabled && <FiLock className="text-gray-400" title="Select parent column first" />}
                    {label}
                  </button>
                );
              })}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default ColumnSelector;